<template>

	<div>

		<van-button @click="publish">发布</van-button>

		<van-cell-group inset>
			<van-field v-model="title" label="标题" placeholder="请输入标题" />

			<van-field v-model="content" rows="1" autosize label="内容" type="textarea" placeholder="请输入内容" />

			<van-field v-model="cate_name" is-link readonly label="分类" placeholder="选择分类" @click="showPicker = true" />







			<van-cell>
				<van-radio-group v-model="poster_type" direction="horizontal">
					<van-radio :name="item.value" v-for="item in typeData">{{item.text}}</van-radio>

				</van-radio-group>

			</van-cell>


			<van-cell>

<!--  上传图片 -->
<!-- 原生  本地选图障眼法 
前端实现图片预览 -->
<!-- <div class="upload">
	<input type="file" id="file" hidden @change="getImg" />
	<label for="file">
		<img src="@/assets/user.png" alt="">
	</label>
</div> -->

<van-uploader v-model="fileList" multiple  :after-read="read" />

			</van-cell>

		</van-cell-group>













		<van-popup v-model:show="showPicker" round position="bottom">
			<van-picker :columns="cateListDate" @cancel="showPicker = false" @confirm="onConfirm" />
		</van-popup>

	</div>
</template>

<script setup>
	import {
		computed,
		ref,
		watch
	} from 'vue';
	import useCate from '@/views/home/cate.js'
	import {
		add_article
	} from '@/api/index.js'
import {get_upload_token,upload as uploadApi} from '@/api/upload'
	let {
		cate_list
	} = useCate()
import { v6 as uuidv6 } from 'uuid';


	// let  cateListDate = [
	//   // { text: '杭州', value: 'Hangzhou' },
	//   // { text: '宁波', value: 'Ningbo' },
	//   // { text: '温州', value: 'Wenzhou' },
	//   // { text: '绍兴', value: 'Shaoxing' },
	//   // { text: '湖州', value: 'Huzhou' },
	// ];

	// name  + _id  
	// text +   value

	const cateListDate = computed(function() {

		return cate_list.value.map(v => {
			return {
				text: v.name,
				value: v._id
			}
		})
	})



	const cate_name = ref('');
	const cate_id = ref('');
	const title = ref('');
	const content = ref('');
	const poster_type = ref('1')

	const imageSrc = ref([]);
  const fileList = ref([
     
    ]);


	const showPicker = ref(false);
	const typeData = [{
		text: '无图',
		value: 0
	}, {
		text: '左字右图',
		value: 1
	}, {
		text: '左图右字',
		value: 2
	}, {
		text: '一个大图',
		value: 3
	}, {
		text: '3图',
		value: 4
	}]

	// 0    无图
	// 1  左字右图
	// 2 左图右字
	// 3  一个大图在下
	// 4.  3图

	const onConfirm = ({
		selectedOptions
	}) => {
		showPicker.value = false;
		cate_name.value = selectedOptions[0].text;
		cate_id.value = selectedOptions[0].value;
	};
	// 前端预览图片  
	
	function getImg(e){
		
		console.dir(e.target.files[0]) //  file对象
		
		let file = e.target.files[0]
		// create Object  URL
		// 创建一个 当前环境下file对象的url映射  
		// 跟当前的环境绑定 
		  
		  // 同步的  速度快 代码少  只能跟当前的环境绑定  
		console.log(
		URL.createObjectURL(file)
		)
		
		// 麻烦  异步  
		
		let filereader = new FileReader()
		
		// filereader.readAsArrayBuffer(file)
		filereader.readAsDataURL(file)
		
		filereader.onload = function(e){
			
			console.log(e.target.result)
			
			
			
		}
		
		
	}


//   选择既上传

function read(e){
	
	
	upload(e.file)
	
}


//  获取上传token

function getUploadToken (){
	
	return new Promise(async function(resolve,reject){
		
		let uploadToken = localStorage.getItem('uploadToken')
		let uploadTokenTime = localStorage.getItem('uploadTokenTime')||0;
		
         let now = new Date().getTime()
		 
		 if(uploadToken&&uploadTokenTime>now){
			 //  如果有老token  并且没过期  
			 resolve(uploadToken)
		 }else{
			 
			let {token} = await get_upload_token();
			 localStorage.setItem('uploadToken',token)  
			 localStorage.setItem('uploadTokenTime',now+6*60*60*1000)
			 
			  resolve(token)
			 
		 }

		
	})
	
}

//  随机文件名 

async function upload(file){
	
	const formdata = new FormData()

	
	let UploadToke = await getUploadToken()
	formdata.append('token',UploadToke)
	formdata.append('file',file)
	formdata.append('key',uuidv6())
	uploadApi(formdata).then(res=>{
	      console.log(import.meta.env.VITE_IMG_URL+  res.key)
		  
		  fileList.value = fileList.value.filter(v=>{
		  	  return v.url
		    })
		  

		  fileList.value.push({
			  url:import.meta.env.VITE_IMG_URL+  res.key,
			  isImage: true 
		  })

	})
	
	
}



	function publish() {
// console.log(fileList)

// let _fileList = fileList.value.map(v=>{
	
// 	return v.file
// })




// console.log(_fileList)
		console.log(title)
		console.log(content)
		console.log(cate_name)
		console.log(cate_id)
		console.log(poster_type)
		console.log(imageSrc)
		
	

		add_article({
			title: title.value,
			content: content.value,
			cate_name: cate_name.value,
			cate_id: cate_id.value,
			poster_type: poster_type.value,
			imageSrc: fileList.value.map(v=>{
				return v.url
			})
		}).then(res => {
			console.log(res)
		})




	}
</script>

<style>
	.upload{
		width: 100px;
		height: 100px;
		position: relative;
		& input{
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			z-index: 0;
			
		}
		
		& img{
			width: 100%;
			height: 100%;
		}
	}
</style>